from Products.CMFCore.utils  import getToolByName
from Products.CMFCore.permissions import View
import base64
import urllib
import json
class Buy:
    def __init__(self,context,request):
        self.context = context
        self.request = request
    def __call__(self):
        mt = getToolByName(self.context, 'portal_membership')
        wtool = getToolByName(self.context, 'portal_workflow')
        if mt.isAnonymousUser():
            return '{"Status":"Error","Message":"Please login first "}' 
        uid = self.request.get('id', '')
        chapter = self.context.reference_catalog.lookupObject(uid)
        if chapter == None or uid=='':
            return '{"Status":"Error","Message":"ID Invalid "}'
        #check Whether the payment published  
        #TODO maybe  here needn't to check because configure.zcml-->permission="zope2.View"
        review_state = wtool.getInfoFor(chapter, "review_state", "")
        if review_state not in ('published'):
            return '{"Status":"Error","Message":"This book is not published"}'
        
        redirect = '%s/chapterpages?json&id=%s' % (self.context.absolute_url(),uid )
        
        if chapter.price==None or chapter.price==0.0:
            return '{"Status":"Error","Message":"This book is free.","Redirect":"%s"}' % redirect
        # If you publish the comics  chapter 
        # the pages will be published  automatically according to price

        list = chapter.contentValues()
        canRead = True
        for item in list:
            if mt.checkPermission(View,item) == None:
                canRead = False
                break
        if canRead: # means user already buy..
            return '{"Status":"Error","Message":"Already buy.","Redirect":"%s"}' % redirect
        #TODO:ToBuy
        
        # get useracount 'a name
        member = mt.getAuthenticatedMember()
        username = member.getUserName()
        userAccount = 'account-%s' % username
        
        if mt.hasProperty(userAccount)==False: # Create user Account
            mt.manage_addProperty(userAccount,0.0,'float')
        # get user's account
        account = 0.0
        account = mt.getProperty(userAccount)
        
        #Insufficient balance
        if account <chapter.price: 
            return '{"Status":"Error","Message":"%s:%s Insufficient balance"}' % (username,account)
        
        
        
        #TODO lack transaction to manage this deal
        account = account - chapter.price
        # set chapter's view role to the user
        chapter.manage_setLocalRoles(username, ["Reader",])
        # save balance
        mt.manage_changeProperties({userAccount:account})
        # reindex objectsecurity
        chapter.reindexObjectSecurity()
        
        
        return '{"Status":"Success","Message":"Buy Success","Redirect":"%s"}' % redirect
        
class Chongzhi:
    def __init__(self,context,request):
        self.context = context
        self.request = request
    def __call__(self):
        mt = getToolByName(self.context, 'portal_membership')
        if mt.isAnonymousUser():
            return '{"Status":"Error","Message":"Please login first "}'
        postData = self.request.get('postData', '')
        if postData == '':
            return '{"Status":"Error","Message":"lack postData"}'
        postData = base64.encodestring(postData)
        postDict = {}
        params = json.dumps(postDict)
        # check from apple
        url = urllib.urlopen('https://sandbox.itunes.apple.com/verifyReceipt',params)
        resultString = url.read()
        result = json.loads(resultString)
        if result['status'] !=0:
            return json.dumps( result )
        
        member = mt.getAuthenticatedMember()
        username = member.getUserName()
#        username = 'lisi'
        userAccount = 'account-%s' % username
        if mt.hasProperty(userAccount)==False: # Create user Account
            mt.manage_addProperty(userAccount,0.0,'float')
        account = 0.0
        account = mt.getProperty(userAccount)
        
        receipt = result['receipt']
        buyProduct = receipt['product_id']
        # add account
        if buyProduct == 'book.coin2':
            account = account + 100
        elif buyProduct == 'book.coin3':
            account = account + 600
        elif buyProduct == 'book.coin4':
            account = account + 1300
        elif buyProduct == 'book.coin5':
            account = account + 2000
        elif buyProduct == 'book.coin6':
            account = account + 3500
        # save user account
        mt.manage_changeProperties({userAccount:account})
        
        return '{"Status":"Success","Message":"%s \'s account is %s"}' % (username,account)
            
        
        

        
        